package com.situ.springboot.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situ.springboot.mapper.UserMapper;
import com.situ.springboot.pojo.entity.User;
import com.situ.springboot.pojo.query.UserQuery;
import com.situ.springboot.service.IUserService;
import com.situ.springboot.util.PageResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements IUserService {
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;


    @Override
    public List<User> selectAll() {
        return userMapper.selectAll();
    }

    /*@Override
    public PageInfo list(UserQuery userQuery) {
        int offset = (userQuery.getPage() - 1) * userQuery.getLimit();
        List<User> list = userMapper.list(offset, userQuery.getLimit(), userQuery);
        int totalCount = userMapper.selectTotalCount(userQuery);
        return PageInfo.ok(totalCount, list);
    }*/

    @Override
    public PageResult list(UserQuery userQuery) {
        //记录开始时间
        //long begin = System.currentTimeMillis();

        //使用PageHelper开启分页
        PageHelper.startPage(userQuery.getPage(), userQuery.getLimit());
        //开启分页之后 LIMIT offset,pageSize 这个代码PageHelper帮我们做了
        List<User> list = userMapper.list(userQuery);
        //查找总数量PageHelper会自动帮我们完成
        //int totalCount = userMapper.selectTotalCount(userQuery);
        PageInfo pageInfo = new PageInfo(list);
        int totalCount = (int) pageInfo.getTotal();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //记录结束时间
       /* long end = System.currentTimeMillis();
        long takeTime = end - begin;
        if (takeTime >= 3000) {
            logger.error("===========执行结束，耗时{}毫秒===========", takeTime);
        } else if (takeTime >= 2000) {
            logger.warn("===========执行结束，耗时{}毫秒===========", takeTime);
        } else {
            logger.info("===========执行结束，耗时{}毫秒===========", takeTime);
        }*/

        return PageResult.ok(totalCount, list);
    }

    @Override
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        userMapper.deleteAll(ids);
    }

    @Override
    public void add(User user) {
        userMapper.add(user);
    }

    @Override
    public User selectById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public void update(User user) {
        userMapper.update(user);
    }

    @Override
    public User login(String name, String password) {
        return userMapper.login(name, password);
    }
}
